package com.google.code.pathlet.eshop.config.web;

import java.io.IOException;
import java.net.URL;

import com.google.code.pathlet.core.Module;
import com.google.code.pathlet.core.ModuleManager;
import com.google.code.pathlet.web.PathletAjaxFilter;
import com.google.code.pathlet.web.widget.ResponseLevel;
import com.google.code.pathlet.web.widget.ResponseMessage;

public class PartyModuleAction {
	
	private String partyVersion;


	public String getPartyVersion() {
		return partyVersion;
	}

	public void setPartyVersion(String partyVersion) {
		this.partyVersion = partyVersion;
	}

	/**
	 * reload one specific module. The moduleId property will be use to indicated the reload module.
	 * @return
	 * @throws IOException
	 */
	public String getVersion() {
		Module partyModule = PathletAjaxFilter.getModuleManager().getModule("party");
		URL url = partyModule.getClassPaths()[0];
		String urlStr = url.toString();

		if(urlStr.endsWith("v1/")) {
			return "1";
		}
		else if(urlStr.endsWith("v2/")) {
			return "2";
		}
		else {
			return "unkown";
		}
	}
	
	/**
	 * Whole container will be reload, and the configuration of this container will be reloaded in this process.
	 * @return
	 * @throws IOException
	 */
	public ResponseMessage applyVersion() throws Exception {
		ModuleManager mm = PathletAjaxFilter.getModuleManager();
		Module partyModule = mm.getModule("party");
		URL url = partyModule.getClassPaths()[0];
		String urlStr = url.toString();
		String newurl;
		if("1".equals(partyVersion)) {
			newurl = urlStr.subSequence(0,  urlStr.length() - 3) + "v1/";
		}
		else if("2".equals(partyVersion)) {
			newurl = urlStr.subSequence(0,  urlStr.length() - 3) + "v2/";
		}
		else {
			throw new Exception("Unable to parse the version from request!");
		}
		
		if(newurl.equals(urlStr) == false) {
			//stop the party module and remove it
			mm.stopModule(partyModule.getId());
			mm.removeModule(partyModule.getId());
			
			//Change the party 
			partyModule.setClassPaths(new URL[]{new URL(newurl)});
			mm.addModule(partyModule);
			mm.startModule(partyModule.getId());
			return new ResponseMessage(ResponseLevel.INFO, "New module version apply Success!");
		}
		else {
			return new ResponseMessage(ResponseLevel.ERROR, "Please select the different version!");
		}
		
	}

}